
import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:sp_util/sp_util.dart';
import 'package:stop_watch_timer/stop_watch_timer.dart';
import 'package:yp/Xwidgets/button_widget.dart';
import 'package:yp/Xwidgets/cache_image.dart';
import 'package:yp/Xwidgets/line.dart';
import 'package:yp/Xwidgets/pay_bottom_sheet.dart';
import 'package:yp/Xwidgets/shop.dart';
import 'package:yp/config/config.dart';
import 'package:yp/config/rules.dart';
import 'package:yp/config/style.dart';
import 'package:yp/helper.dart';
import 'package:yp/pages/order/pre_sale_order/pre_sale_logic.dart';
import 'package:yp/services/api.dart';
import 'package:yp/widgets/dialog.dart';

import '../../../router.dart';
import 'pre_sale_state.dart';

final List orderStateList = ['待付款', '待发货', '拼团中', '已发货', '待自提', '待评价', '已完成'];

class PreSalePage extends StatefulWidget {
  @override
  _PreSalePageState createState() => _PreSalePageState();
}

class _PreSalePageState extends State<PreSalePage>
    with SingleTickerProviderStateMixin {
  TabController _controller;

  var _tabList = [
    Tab(text: '全部'),
    Tab(text: '待付款'),
    Tab(text: '待配送/自提'),
    Tab(text: '待送达'),
    Tab(text: '待评价'),
    Tab(text: '售后'),
  ];

  @override
  void initState() {
    super.initState();

    _controller =
        TabController(initialIndex: 0, length: _tabList.length, vsync: this);
  }

  @override
  void dispose() async {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Get.put(PreSaleLogic());
    // final state = Get.find<OrderLogic>().state;
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Config.mainColor,
          brightness: Brightness.light,
          iconTheme: IconThemeData(color: Colors.white),
          title: Text(
            "预售订单",
            style: TextStyle(color: Colors.white, fontSize: 32.sp),
          ),
          centerTitle: true,
          elevation: 0,
        ),
        body: Container(
          color: const Color(0xffffffff),
          child: GetBuilder<PreSaleLogic>(builder: (logic) {
            return Column(
              children: [
                _tabHeadder(),
                YpLine(
                  height: 20,
                  thickness: 20,
                  color: EsColors.BackGroundSecondary,
                ),
                _orderList(),
              ],
            );
          }),
        ));
  }

  /// 获取不同状态下的订单状态数组
  int _getOrderState(int type) {
    switch (type) {
      case 0:
        return 0;
        break;
      case 1:
        return 1;
        break;
      case 2:
        return 2;
        break;
      case 3:
        return 3;
        break;
      case 4:
        return 4;
        break;
      default:
        return 17;
        break;
    }
  }

  ///  tab栏切换的头部
  Widget _tabHeadder() {
    return Container(
      color: EsColors.White,
      padding: const EdgeInsets.symmetric(horizontal: 15),
      child: ExtendedTabBar(
        tabs: List<Widget>.generate(
            _controller.length, (int index) => _tabList[index]),
        controller: _controller,
        labelPadding: EdgeInsets.zero,
        labelColor: EsColors.Primary,
        isScrollable: false,
        unselectedLabelColor: EsColors.TitleSecondary,
        indicatorSize: TabBarIndicatorSize.label,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        indicator: const ExtendedUnderlineTabIndicator(
            // size: 30,
            borderSide: BorderSide(color: EsColors.Primary, width: 2)),
      ),
    );
  }

  /// 下边对应的列表
  Widget _orderList() {
    return Expanded(
      child: TabBarView(
          controller: _controller,
          children: List<Widget>.generate(
              _controller.length,
              (int index) => OrderList(
                    orderState: _getOrderState(index),
                    tabIndex: index,
                  )).toList()),
    );
  }
}

class OrderList extends StatefulWidget {
  /// 能够获取的数组  item状态随机
  final int orderState;
  final int tabIndex;

  const OrderList({
    Key key,
    this.orderState,
    this.tabIndex,
  }) : super(key: key);

  @override
  _OrderListState createState() => _OrderListState();
}

class _OrderListState extends State<OrderList>
    with AutomaticKeepAliveClientMixin {
  List _orderInfoList = [];

  int page = 1;

  RefreshController _refreshController =
      RefreshController(initialRefresh: true);

  getOrderList() {
    var params = widget.orderState != 17
        ? {
            "client_type": 1,
            "page": page,
            "page_size": 10,
            "order_status": widget.orderState,
            "access_token": SpUtil.getString('token'),
            "channel_num_id": 99,
            "use_platform": 2,
            "so_sign": 14, // 订单类型订单类型：0 普通订单,14 预售订单
          }
        : {
            "client_type": 1,
            "page": page,
            "page_size": 10,
            "order_status": widget.orderState,
            "access_token": SpUtil.getString('token'),
            "channel_num_id": 99,
            "use_platform": 2,
          };
    Api.searchOrderList(params).listen((event) {
      print('----------------------------------');
      print(event);
      print(params);
      print('order_status ==> ${widget.orderState}');
      print('----------------------------------');

      if (mounted) {
        setState(() {
          if (event['orders'] != null && event['orders'].length > 0) {
            _orderInfoList.addAll(event['orders']);

            page++;
            _refreshController.refreshCompleted();
            _refreshController.loadComplete();
          } else {
            // _orderInfoList = [];
            _refreshController.refreshCompleted();
            _refreshController.loadNoData();
          }
        });
      }
    });
  }

  void _onRefresh() async {
    setState(() {
      _orderInfoList = [];
      page = 1;
    });

    getOrderList();
  }

  void _onLoading() async {
    getOrderList();
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(body: GetBuilder<PreSaleLogic>(builder: (logic) {
      return SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: ClassicHeader(),
        footer: ClassicFooter(),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: _orderInfoList.length > 0
            ? ListView.separated(
                itemBuilder: (context, index) {
                  return _orderItem(_orderInfoList, index, logic);
                },
                separatorBuilder: (context, index) => YpLine(
                    height: 20,
                    thickness: 20,
                    color: EsColors.BackGroundSecondary),
                itemCount: _orderInfoList.length,
              )
            : Center(
                child: Text(
                  '暂无数据',
                  style: TextStyle(
                    color: Color(0xff999999),
                    fontSize: 28.w,
                  ),
                ),
              ),
      );
    }));
  }

  /// 订单item
  // Widget _orderItem(List info, int index) {
  //   return Container(
  //     color: EsColors.White,
  //     padding: const EdgeInsets.only(bottom: 14),
  //     child: Column(
  //       children: [
  //         ShopName(
  //           info[index]['ec_shop_name'],
  //           // shopState: info['shopState'],
  //           orderState: info[index]['operate_status_name'],
  //         ),
  //         YpLine(),
  //         GestureDetector(
  //           behavior: HitTestBehavior.opaque,
  //           onTap: () {
  //             Get.toNamed(RouteConfig.orderDetial, arguments: {
  //               'id': info[index]['order_num_id'],
  //               'status:': info[index]['order_status'],
  //             });
  //             print('查看购买商品');
  //           },
  //           child: Container(
  //             margin: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
  //             child: Row(
  //               children: [
  //                 Expanded(
  //                     child: Wrap(
  //                   spacing: 6,
  //                   children: List.generate(
  //                       info[index]['item_details'].length > 5
  //                           ? 5
  //                           : info[index]['item_details'].length,
  //                       (indexs) => CachedImage(
  //                             width: (MediaQuery.of(context).size.width / 7),
  //                             height: MediaQuery.of(context).size.width / 7,
  //                             path: info[index]['item_details'][indexs]
  //                                 ['item_picture'],
  //                             border: Border.all(
  //                                 color: EsColors.BackGroundSecondary,
  //                                 width: 1),
  //                           )),
  //                 )),
  //                 Text(
  //                   '共' + (info[index]['item_details'].length).toString() + '件',
  //                   maxLines: 1,
  //                   overflow: TextOverflow.ellipsis,
  //                   style: TextStyle(
  //                       color: EsColors.ContentSecondary,
  //                       fontSize: EsSizes.SM,
  //                       fontWeight: EsFontWeights.Normal),
  //                 )
  //               ],
  //             ),
  //           ),
  //         ),
  //         Row(
  //           children: [
  //             SizedBox(width: 12),
  //             RichText(
  //               maxLines: 1,
  //               overflow: TextOverflow.ellipsis,
  //               text: TextSpan(
  //                   text: '${rules('a1', info[index]) ? '应付' : '实付'}：￥',
  //                   style: TextStyle(
  //                       fontSize: EsSizes.XS,
  //                       color: EsColors.TitleSecondary,
  //                       fontWeight: EsFontWeights.Normal),
  //                   children: <TextSpan>[
  //                     TextSpan(
  //                         text: rules('a1', info[index])
  //                             ? info[index]['need_pay_amount'].toString()
  //                             : info[index]['real_pay_amount'].toString(),
  //                         style: TextStyle(
  //                             fontSize: EsSizes.LG,
  //                             color: EsColors.TitleSecondary,
  //                             fontWeight: EsFontWeights.Medium)),
  //                   ]),
  //             ),
  //             Expanded(child: SizedBox()),
  //             ////按钮
  //             Padding(
  //               padding: const EdgeInsets.only(right: 12),
  //               child: _orderProgress(info[index]),
  //             )
  //           ],
  //         )
  //       ],
  //     ),
  //   );
  // }

  /// 订单item
  Widget _orderItem(List info, int index, PreSaleLogic logic) {
    return GestureDetector(
      onTap: () {
        /// 查看商品详情
        print('跳转订单详情。。。');
        // print(info[index]['tml_num_id']);
        // print(info[index]['order_status']);
        // return;
        if (widget.orderState == 17) {
          Get.toNamed(RouteConfig.applyDetail, arguments: {
            // 'id': info[index]['tml_num_id'],
            'id': info[index]['order_num_id'],
            "ordertype": 1,
            'status': 5,
          }).then((value) {
            _onRefresh();
            print('========123afdfafafasfd========>');
          });
        } else {
          Get.toNamed(RouteConfig.orderDetial, arguments: {
            // 'id': info[index]['tml_num_id'],
            'id': info[index]['order_num_id'],
            'status:': info[index]['order_status'],
          }).then((value) {
            _onRefresh();
            print('========123afdfafafasfd========>');
          });
        }
      },
      child: Container(
        color: EsColors.White,
        padding: const EdgeInsets.only(bottom: 14),
        child: Column(
          children: [
            ShopName(
              info[index]['ec_shop_name'],
              // shopState: info['shopState'],
              orderState: info[index]['order_status_name'],
            ),
            YpLine(),
            Container(
              padding: EdgeInsets.symmetric(
                horizontal: 30.w,
                vertical: 15.w,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "订单号：${info[index]['order_num_id']}",
                    style: TextStyle(
                      color: Color(0xff666666),
                      fontSize: 24.sp,
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      Clipboard.setData(ClipboardData(
                          text: '${info[index]['order_num_id']}'));
                      toast("复制成功");
                    },
                    child: Text(
                      "复制",
                      style: TextStyle(
                        color: Color(0xff666666),
                        fontSize: 24.sp,
                      ),
                    ),
                  )
                ],
              ),
            ),
            GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  if (widget.orderState == 17) {
                    Get.toNamed(RouteConfig.applyDetail, arguments: {
                      // 'id': info[index]['tml_num_id'],
                      'id': info[index]['order_num_id'],
                      "ordertype": 1,
                      'status': 5,
                    }).then((value) {
                      print('========123afdfafafasfd========>');
                    });
                  } else {
                    Get.toNamed(RouteConfig.orderDetial, arguments: {
                      // 'id': info[index]['tml_num_id'],
                      'id': info[index]['order_num_id'],
                      'status:': info[index]['order_status'],
                    });
                  }
                  print('查看购买商品');
                },
                child: info[index]['item_details'].length > 1
                    ? duoproduct(info, index)
                    : danproduct(info, index)),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 30.w),
              margin: EdgeInsets.only(bottom: 30.w),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '共' + (info[index]['item_details'].length).toString() + '件',
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: EsColors.ContentSecondary,
                        fontSize: EsSizes.SM,
                        fontWeight: EsFontWeights.Normal),
                  ),
                  RichText(
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    text: TextSpan(
                        text: '${rules('a1', info[index]) ? '应付' : '实付'}：￥',
                        style: TextStyle(
                            fontSize: EsSizes.XS,
                            color: EsColors.TitleSecondary,
                            fontWeight: EsFontWeights.Normal),
                        children: <TextSpan>[
                          TextSpan(
                              text: rules('a1', info[index])
                                  ? info[index]['need_pay_amount'].toString()
                                  : info[index]['real_pay_amount'].toString(),
                              style: TextStyle(
                                  fontSize: EsSizes.XS,
                                  color: EsColors.TitleSecondary,
                                  fontWeight: EsFontWeights.Medium)),
                        ]),
                  ),
                ],
              ),
            ),
            Row(
              children: [
                SizedBox(width: 12),
                // RichText(
                //   maxLines: 1,
                //   overflow: TextOverflow.ellipsis,
                //   text: TextSpan(
                //       text: '${rules('a1', info[index]) ? '应付' : '实付'}：￥',
                //       style: TextStyle(
                //           fontSize: EsSizes.XS,
                //           color: EsColors.TitleSecondary,
                //           fontWeight: EsFontWeights.Normal),
                //       children: <TextSpan>[
                //         TextSpan(
                //             text: rules('a1', info[index])
                //                 ? info[index]['need_pay_amount'].toString()
                //                 : info[index]['real_pay_amount'].toString(),
                //             style: TextStyle(
                //                 fontSize: EsSizes.LG,
                //                 color: EsColors.TitleSecondary,
                //                 fontWeight: EsFontWeights.Medium)),
                //       ]),
                // ),
                Expanded(child: SizedBox()),
                ////按钮
                Padding(
                  padding: const EdgeInsets.only(right: 12),
                  child: _orderProgress(info[index], logic),
                )
              ],
            )
          ],
        ),
      ),
    );
  }

  Widget danproduct(info, index) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Wrap(
            spacing: 6,
            children: List.generate(
              info[index]['item_details'].length > 5
                  ? 5
                  : info[index]['item_details'].length,
              (indexs) => CachedImage(
                width: (MediaQuery.of(context).size.width / 7),
                height: MediaQuery.of(context).size.width / 7,
                path: info[index]['item_details'][indexs]['item_picture'],
                border:
                    Border.all(color: EsColors.BackGroundSecondary, width: 1),
              ),
            ),
          ),
          SizedBox(
            width: 20.w,
          ),
          Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                width: 500.w,
                height: 50.w,
                child: Text(
                  info[index]['item_details'][0]['item_name'],
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              Container(
                width: 500.w,
                child: Text(
                  info[index]['item_details'][0]['spec_nature_info'] == null
                      ? 'X${info[index]['item_details'][0]['qty'].toStringAsFixed(0)}'
                      : info[index]['item_details'][0]['spec_nature_info'] +
                          ' X${info[index]['item_details'][0]['qty'].toStringAsFixed(0)}',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          )
        ],
      ),
    );
  }

  Widget duoproduct(info, index) {
    return Container(
      margin: const EdgeInsets.only(
        top: 12,
        left: 12,
        right: 12,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: List.generate(
          info[index]['item_details'].length > 5
              ? 5
              : info[index]['item_details'].length,
          (indexs) => Container(
            padding: EdgeInsets.only(bottom: 10.w),
            margin: EdgeInsets.only(bottom: 30.w),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: Color(0xffE6E8E8),
                ),
              ),
            ),
            child: Row(
              children: [
                CachedImage(
                  width: 100.w,
                  height: 100.w,
                  path: info[index]['item_details'][indexs]['item_picture'],
                  border: Border.all(
                    color: EsColors.BackGroundSecondary,
                    width: 1,
                  ),
                ),
                Expanded(
                  child: Container(
                    height: 120.w,
                    margin: EdgeInsets.only(left: 20.w),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          info[index]['item_details'][indexs]['item_name'],
                          style: TextStyle(
                            fontSize: 24.sp,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        Row(
                          children: [
                            Text(
                              "¥${info[index]['item_details'][indexs]['total_trade_amount']}",
                              style: TextStyle(
                                fontSize: 24.sp,
                                color: Config.mainColor,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                            Text(
                              " x${info[index]['item_details'][indexs]['qty']}"
                                  .replaceAll(".0", ""),
                              style: TextStyle(
                                fontSize: 24.sp,
                                color: Colors.black,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ],
                        )
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 订单进度 不同状态下的右下角按钮
  // Widget _orderProgress(info) {
  //   return Row(
  //     children: [
  //       Visibility(
  //         visible: rules('a4', info),
  //         child: Row(children: [
  //           TimeButton(info, context),
  //           SizedBox(width: 12.w),
  //         ]),
  //       ), //去付款
  //       // EsOutLineButton(
  //       //   '订单详情',
  //       //   normal: true,
  //       //   onTap: () {
  //       //     print('订单详情');
  //       //   },
  //       // ),
  //       // SizedBox(width: 12.w),

  //       Visibility(
  //         visible: rules('a7', info),
  //         child: Row(children: [
  //           EsOutLineButton(
  //             '拼团详情',
  //             onTap: () {
  //               print('拼团详情');
  //             },
  //           ),
  //           SizedBox(width: 12.w),
  //         ]),
  //       ),

  //       Visibility(
  //         visible: rules('a2', info),
  //         child: Row(children: [
  //           EsOutLineButton(
  //             '查看物流',
  //             normal: true,
  //             onTap: () {
  //               Get.toNamed(RouteConfig.logistics, parameters: {
  //                 'tmlId': info["order_num_id"],
  //                 'transCode': info["ship_tran_no_by_order_num_ids"]
  //               });
  //               print('查看物流');
  //             },
  //           ),
  //           SizedBox(width: 12.w),
  //         ]),
  //       ), //查看物流

  //       Visibility(
  //         visible: rules('a3', info),
  //         child: Row(children: [
  //           EsOutLineButton(
  //             '确认收货',
  //             bgColor: EsColors.Primary,
  //             textColor: EsColors.White,
  //             onTap: () {
  //               print('确认收货');
  //             },
  //           ),
  //           SizedBox(width: 12.w),
  //         ]),
  //       ), //确认收货
  //       Visibility(
  //         visible: rules('a6', info),
  //         child: Row(children: [
  //           RichText(
  //             maxLines: 1,
  //             overflow: TextOverflow.ellipsis,
  //             text: TextSpan(
  //                 text: '自提码：',
  //                 style: TextStyle(
  //                     fontSize: EsSizes.XS,
  //                     color: EsColors.TitleSecondary,
  //                     fontWeight: EsFontWeights.Normal),
  //                 children: <TextSpan>[
  //                   TextSpan(
  //                       text: info['verification_code'].toString(),
  //                       style: TextStyle(
  //                           fontSize: EsSizes.LG,
  //                           color: EsColors.TitleSecondary,
  //                           fontWeight: EsFontWeights.Medium)),
  //                 ]),
  //           ),
  //           SizedBox(width: 12.w),
  //         ]),
  //       ), //自提码

  //       // EsOutLineButton(
  //       //   '再来一单',
  //       //   onTap: () {
  //       //     print('再来一单');
  //       //   },
  //       // ),
  //       // SizedBox(width: 12.w),
  //       Visibility(
  //         visible: rules('a5', info) && widget.tabIndex != 5,
  //         child: Row(children: [
  //           EsOutLineButton(
  //             '晒单评价',
  //             bgColor: EsColors.Primary,
  //             textColor: EsColors.White,
  //             onTap: () {
  //               print('晒单评价');
  //             },
  //           ),
  //           SizedBox(width: 12.w),
  //         ]),
  //       ), //评价

  //       // EsOutLineButton(
  //       //   '开具发票',
  //       //   normal: true,
  //       //   onTap: () {
  //       //     print('开具发票');
  //       //   },
  //       // ),
  //       // SizedBox(width: 12.w),
  //     ],
  //   );
  // }
  Widget _orderProgress(info, PreSaleLogic logic) {
    return Row(
      children: [
        Visibility(
          visible: rules('a4', info),
          child: Row(children: [
            TimeButton(info, context),
            SizedBox(width: 12.w),
          ]),
        ), //去付款
        // EsOutLineButton(
        //   '订单详情',
        //   normal: true,
        //   onTap: () {
        //     print('订单详情');
        //   },
        // ),
        // SizedBox(width: 12.w),

        Visibility(
          // visible: rules('a7', info),
          visible: false,
          child: Row(children: [
            EsOutLineButton(
              '拼团详情',
              onTap: () {
                print('拼团详情');
              },
            ),
            SizedBox(width: 12.w),
          ]),
        ),

        Visibility(
          visible: rules('a2', info),
          child: Row(children: [
            EsOutLineButton(
              '查看物流',
              normal: true,
              onTap: () {
                Get.toNamed(RouteConfig.logistics, parameters: {
                  // 'tmlId': info["tml_num_id"],
                  'tmlId': info['order_num_id'],
                  'transCode': info["ship_tran_no_by_tml_num_ids"]
                });
                print('查看物流');
              },
            ),
            SizedBox(width: 12.w),
          ]),
        ), //

        if (info["order_status"] == 1 && info['unpay_button_type'] == 1)
          Row(children: [
            EsOutLineButton(
              '取消订单 ',
              normal: true,
              onTap: () {
                YpShowDialog.normalConfirm(context, '确定取消订单？',
                    normalOrder: false, leftCallback: () {
                  var params = {
                    'tml_num_id': info['order_num_id'],
                    'usr_num_id': SpUtil.getInt('empeNumId'),
                  };
                  Api.closeOrder(params).listen((event) {
                    if (event['code'] == 0) {
                      toast("操作成功");
                      logic.onReady();
                    } else {
                      toast(event["message"]);
                    }
                  });
                  print('下一步');
                });
              },
            ),
            SizedBox(width: 12.w),
          ]), //

        if (info["install_service_sign"] == 1 && info["order_status"] != 16)
          Row(children: [
            EsOutLineButton(
              '查看工单',
              normal: true,
              onTap: () {
                // toast("小程序的也有问题");
                Get.toNamed(RouteConfig.gongdan, arguments: {
                  'tmlId': info['order_num_id'],
                });
              },
            ),
            SizedBox(width: 12.w),
          ]), //

        Visibility(
          visible: rules('a3', info),
          child: Row(children: [
            EsOutLineButton(
              '确认收货',
              bgColor: EsColors.Primary,
              textColor: EsColors.White,
              onTap: () {
                print('确认收货');
              },
            ),
            SizedBox(width: 12.w),
          ]),
        ), //确认收货
        Visibility(
          visible: rules('a6', info),
          child: Row(children: [
            RichText(
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              text: TextSpan(
                  text: '自提码：',
                  style: TextStyle(
                      fontSize: EsSizes.XS,
                      color: EsColors.TitleSecondary,
                      fontWeight: EsFontWeights.Normal),
                  children: <TextSpan>[
                    TextSpan(
                        text: info['verification_code'].toString(),
                        style: TextStyle(
                            fontSize: EsSizes.LG,
                            color: EsColors.TitleSecondary,
                            fontWeight: EsFontWeights.Medium)),
                  ]),
            ),
            SizedBox(width: 12.w),
          ]),
        ), //自提码

        /// 加入购物车
        Visibility(
          visible: rules('a24', info),
          child: Padding(
            padding: const EdgeInsets.only(right: 6),
            child: soSignPayBtn(
              onTap: () {
                info['item_details'].forEach((element) {
                  logic.buyAgain(element, info['ec_shop_num_id']);
                });
                // logic.buyAgain(info);
              },
              text: '加入购物车',
              fontSize: 12,
              showTimerValue: false,
            ),
          ),
        ),

        /// 超级团补差价
        Visibility(
          visible: rules('a23', info),
          child: Padding(
            padding: const EdgeInsets.only(right: 6),
            child: soSignPayBtn(
              onTap: () {
                PreSaleState state = logic.state;
                state.total['all_payment'] = info['need_pay_amount'];
                print(info);
                // return;
                print('card_type:${info['card_type']}');
                print('state.GiftcardList.length:${state.GiftcardList.length}');

                // SpUtil.putString('tml_num_id', info['tml_num_id']);
                SpUtil.putString('order_num_id', info['order_num_id']);
                SpUtil.putDouble('need_pay_amount', info['need_pay_amount']);
                if (info['card_type'] == 1 ||
                    state.GiftcardList.length == 0 ||
                    info['ec_shop_num_id'] != SpUtil.getInt('storeShopNum')) {
                  //直接调起微信支付
                  // logic.goToMoney(info['tml_num_id']);
                  logic.goToMoney(info['order_num_id']);
                  return;
                }
                //如果是 0， 需要查询福利卡，减去福利卡金额  （total_amount）- 福利卡金额
                if (info['card_type'] == 0) {
                  // 福利卡可多选
                  // 如果
                  payBottomSheet.showPay(
                      context, logic.state, logic.goToMoney, logic.setGift,
                      // tmlnumid: info['tml_num_id']);
                      tmlnumid: info['order_num_id']);
                }
              },
              text: '补差价',
              fontSize: 12,
              showTimerValue: false,
            ),
          ),
        ),

        /// 超级团退团
        Visibility(
            visible: rules('a22', info),
            child: Padding(
              padding: const EdgeInsets.only(right: 6),
              child: soSignPayBtn(
                onTap: () {
                  showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return CupertinoAlertDialog(
                        title: Text("提示"),
                        content: Column(
                          children: <Widget>[
                            SizedBox(
                              height: 10,
                            ),
                            Align(
                              child: Text("确定要取消吗?"),
                              alignment: Alignment(0, 0),
                            ),
                          ],
                        ),
                        actions: <Widget>[
                          CupertinoDialogAction(
                            child: Text("否"),
                            onPressed: () {
                              Navigator.pop(context);
                            },
                          ),
                          CupertinoDialogAction(
                            child: Text("是"),
                            onPressed: () {
                              logic.refund(info: info);
                            },
                          ),
                        ],
                      );
                    },
                  );
                },
                text: '退团',
                fontSize: 12,
                showTimerValue: false,
              ),
            )),

        /// 定金预售付预售尾款
        Visibility(
          visible: rules('a21', info),
          child: Padding(
            padding: const EdgeInsets.only(right: 6),
            child: soSignPayBtn(
              onTap: () {
                /// 付尾款日期 balance_start_dtme
                Get.toNamed(RouteConfig.endSaleOrder, arguments: {
                  'shop_id': info['ec_shop_num_id'],
                  'shopnum': 1,
                  'tml_num_id': info['order_num_id'],
                  'isFontSale': false,
                });
              },
              text: '付预售尾款',
              fontSize: 12,
              showTimerValue: false,
            ),
          ),
        ),

        /// 定金预售退预售定金
        Visibility(
            visible: rules('a20', info),
            child: Padding(
              padding: const EdgeInsets.only(right: 6),
              child: soSignPayBtn(
                onTap: () {
                  showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return CupertinoAlertDialog(
                        title: Text("提示"),
                        content: Column(
                          children: <Widget>[
                            SizedBox(
                              height: 10,
                            ),
                            Align(
                              child: Text("确定要取消吗?"),
                              alignment: Alignment(0, 0),
                            ),
                          ],
                        ),
                        actions: <Widget>[
                          CupertinoDialogAction(
                            child: Text("否"),
                            onPressed: () {
                              Navigator.pop(context);
                            },
                          ),
                          CupertinoDialogAction(
                            child: Text("是"),
                            onPressed: () {
                              logic.refund(info: info);
                            },
                          ),
                        ],
                      );
                    },
                  );
                },
                text: '退预售定金',
                fontSize: 12,
                showTimerValue: false,
              ),
            )),

        // EsOutLineButton(
        //   '再来一单',
        //   onTap: () {
        //     print('再来一单');
        //   },
        // ),
        // SizedBox(width: 12.w),
        if (info["comment_type"] == 0 && info["order_status"] != 16)
          Row(children: [
            EsOutLineButton(
              '评价晒单',
              bgColor: EsColors.Primary,
              textColor: EsColors.White,
              onTap: () {
                //评价晒单 跳转
                // print('  评价参数   widget.data = ${widget.data} ');
                var params = {
                  'use_platform': 2,
                  'access_token': SpUtil.getString('token'),
                  'usr_num_id': SpUtil.getInt('empeNumId'),
                };

                Api.viewEvaluationPermission(params).listen((event) {
                  if (event['code'] == 0) {
                    String blackType = event['black_type'].toString();
                    if (!blackType.contains('2')) {
                      Get.toNamed(
                        RouteConfig.pingJiaShaiDan,
                        arguments: info,
                      );
                      return;
                    }
                  } else {
                    toast('评价权限暂时关闭，请联系客服');
                  }
                }, onError: (error) {});
                print('晒单评价');
              },
            ),
            SizedBox(width: 12.w),
          ]),
        if (info["comment_type"] == 2)
          Row(children: [
            EsOutLineButton(
              '查看评价',
              bgColor: EsColors.Primary,
              textColor: EsColors.White,
              onTap: () {
                //评价晒单 跳转
                // print('  评价参数   widget.data = ${widget.data} ');
                var params = {
                  'use_platform': 2,
                  'access_token': SpUtil.getString('token'),
                  'usr_num_id': SpUtil.getInt('empeNumId'),
                };

                Api.viewEvaluationPermission(params).listen((event) {
                  if (event['code'] == 0) {
                    print(info);
                    // return;
                    // String blackType = event['black_type'].toString();
                    Get.toNamed(
                      RouteConfig.viewComments,
                      arguments: info,
                    );
                  } else {
                    toast('评价权限暂时关闭，请联系客服');
                  }
                }, onError: (error) {});
                print('晒单评价');
              },
            ),
            SizedBox(width: 12.w),
          ]),

        if (info["consumer_invoice_sign"] == 1)
          EsOutLineButton(
            '查看发票',
            normal: true,
            onTap: () {
              toast('TODO和小程序保持一致');
              // // return;
              // Get.toNamed(RouteConfig.drawBillPage,
              //     arguments: {'tml_num_id': info['order_num_id']});
            },
          ),
        if (info["consumer_invoice_sign"] == 0 &&
            info["order_status"] != 9 &&
            (info["status_num_id"] == 3 || info["status_num_id"] == 6))
          EsOutLineButton(
            '申请发票',
            normal: true,
            onTap: () {
              print('申请发票${info['order_num_id']}');
              // return;
              Get.toNamed(RouteConfig.drawBillPage,
                  arguments: {'tml_num_id': info['order_num_id']});
            },
          ),
        SizedBox(width: 12.w),
      ],
    );
  }

  @override
  void dispose() async {
    super.dispose();
    _refreshController.dispose();

    print('dispose Finish');
  }

  @override
  bool get wantKeepAlive => true;
}

Widget soSignPayBtn({
  Function onTap,
  String text = '去付款',
  double fontSize,
  bool showTimerValue = true,
  String timerValue = '',
}) {
  return GestureDetector(
    onTap: onTap,
    child: Container(
      decoration: BoxDecoration(
          color: EsColors.Primary, borderRadius: BorderRadius.circular(20.0)),
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
      child: Text(
        showTimerValue ? text + timerValue : text,
        style: TextStyle(
            fontSize: fontSize ?? EsSizes.SM,
            color: EsColors.White,
            fontWeight: EsFontWeights.Normal),
      ),
    ),
  );
}

//倒计时按钮
class TimeButton extends StatefulWidget {
  var info;

  TimeButton(this.info, BuildContext context, {Key key}) : super(key: key);

  @override
  _TimeButtonState createState() => _TimeButtonState();
}

class _TimeButtonState extends State<TimeButton> {
  final _isHours = true;

  final StopWatchTimer _stopWatchTimerDown = StopWatchTimer(
    mode: StopWatchMode.countDown,
    presetMillisecond: StopWatchTimer.getMilliSecFromSecond(10),
    // onChange: (value) => print('onChange $value'),
    // onChangeRawSecond: (value) => print('onChangeRawSecond $value'),
    // onChangeRawMinute: (value) => print('onChangeRawMinute $value'),
    onEnded: () {
      print('onEnded');
    },
  );

  @override
  void initState() {
    _stopWatchTimerDown.onExecute.add(StopWatchExecute.start);
    super.initState();
  }

  @override
  void dispose() async {
    print('这是销毁');
    super.dispose();
    await _stopWatchTimerDown.dispose(); // Need to call dispose function.
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {},
      child: StreamBuilder<int>(
        stream: _stopWatchTimerDown.rawTime,
        initialData: _stopWatchTimerDown.rawTime.value,
        builder: (context, snap) {
          final value = snap.data;
          // print('value');
          // print(snap);
          // DateTime dateTime = DateTime.now();
          // int value = dateTime.add(Duration(hours: 1)).millisecondsSinceEpoch;
          // print('dateTime ==> $dateTime --------------------aa ==> $value');
          // final displayTime = StopWatchTimer.getDisplayTime(value,
          //     hours: _isHours, milliSecond: false);
          return GestureDetector(
            onTap: () {
              final logic = Get.put(PreSaleLogic());
              final state = Get.find<PreSaleLogic>().state;
              logic.state.total['all_payment'] = widget.info['total_amount'];
              print(logic.state.total['all_payment']);
              // return;
              print('card_type:${widget.info['card_type']}');
              print('state.GiftcardList.length:${state.GiftcardList.length}');

              SpUtil.putString('order_num_id', widget.info['order_num_id']);
              SpUtil.putDouble(
                  'need_pay_amount', widget.info['need_pay_amount']);
              if (widget.info['card_type'] == 1 ||
                  state.GiftcardList.length == 0) {
                //直接调起微信支付
                logic.goToMoney(widget.info['order_num_id']);
                return;
              }
              //如果是 0， 需要查询福利卡，减去福利卡金额  （total_amount）- 福利卡金额
              if (widget.info['card_type'] == 0) {
                // 福利卡可多选
                // 如果
                payBottomSheet.showPay(
                    context, logic.state, logic.goToMoney, logic.setGift,
                    tmlnumid: widget.info['order_num_id']);
              }
            },
            child: Container(
              decoration: BoxDecoration(
                  color: EsColors.Primary,
                  borderRadius: BorderRadius.circular(20.0)),
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
              child: Text(
                // '去付款 ' + displayTime,
                '去付款',
                style: const TextStyle(
                    fontSize: EsSizes.SM,
                    color: EsColors.White,
                    fontWeight: EsFontWeights.Normal),
              ),
            ),
          );
        },
      ),
    );
  }
}
